<?php

namespace app\api\logic;

use app\common\exception\BusinessException;
use app\common\model\UserVip;

class Ai
{
    /**
     * ocr
     * @param $param
     * @return array
     * @throws BusinessException
     */
    public function ocr($param)
    {
        // 检查
        if (!isVip()) {
            throw new BusinessException('此功能仅对会员开放');
        }
        $ocrService = getBdBceService('ocr');
        $data = [
            'url' => $param['url'],
            'detect_direction' => 'false',
            'detect_language' => 'false',
            'paragraph' => 'false',
            'probability' => 'false'
        ];
        $responseData = $ocrService->ocrExecute('/rest/2.0/ocr/v1/general_basic', $data);
        $keyword = [];
        if (empty($responseData['words_result_num'])) {
            throw new BusinessException('识别图片失败,请重试');
        }
        foreach ($responseData['words_result'] as $item) {
            $keyword[] = $item['words'];
        }
        return $keyword;
    }

    /**
     * speech
     * @param $param
     * @return array
     * @throws BusinessException
     */
    public function speech($param)
    {
        // 检查
        if (!isVip()) {
            throw new BusinessException('此功能仅对会员开放');
        }

        // 提取参数
        $url = $param['url'];

        // 下载Url地址的语音数据
        $urlBin = file_get_contents($url);
        if (!$urlBin) {
            throw new BusinessException('获取语音数据失败,请重试');
        }

        // 启动识别服务
        $speechService = getBdBceService('speech');

        // 请求参数
        $speech = base64_encode($urlBin);
        $data = [
            'format' => 'm4a',
            'rate' => '16000',
            'channel' => 1,
            'cuid' => uniqid(),
            'dev_pid' => 80001,
            'speech' => $speech,
            'len' => strlen($urlBin),
        ];
        $responseData = $speechService->speechExecute('/pro_api', $data);
        $keyword = [];
        if (empty($responseData['result'])) {
            throw new BusinessException('识别语音失败,请重试');
        }
        foreach ($responseData['result'] as $item) {
            $keyword[] = $item;
        }
        return $keyword;
    }
}